/*
 * @Author: Ping Chou
 * @Date: 2022-01-30 19:46:36
 * @LastEditTime: 2022-02-02 22:00:51
 * @LastEditors: Ping Chou
 * @Description: fetch hooks
 * @FilePath: /dojo-blog/src/useFetch.js
 */
import { useState, useEffect } from 'react'
const useFetch = (url) => {
  const [data, setdata] = useState(null)
  const [isPending, setIsPending] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    console.log('use effect ran')
    const abortCont = new AbortController()
    setTimeout(() => {
      fetch(url, {
        signal: abortCont.signal
      })
        .then((res) => {
          if (!res.ok) {
            throw Error('网络连接错误，请稍后重试')
          }
          return res.json()
        })
        .then((data) => {
          setdata(data)
          setIsPending(false)
          setError(null)
        })
        .catch((err) => {
          if (err.name === 'AbortError') {
            console.log('fetch aborted')
          } else {
            setIsPending(false)
            setError(err.message)
          }
        })
    }, 1000)

    return () => abortCont.abort()
  }, [url])

  return {
    data,
    isPending,
    error
  }
}
export default useFetch
